package com.example.tmapdemo;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.skt.tapi.Tmap.Tmap;
import com.skt.tapi.Tmap.Result.TmapResultRoute;
import com.skt.tapi.Tmap.TOPs.TmapPoint;
import com.skt.tapi.Tmap.constant.NV_ROUTEFARETYPE;
import com.skt.tapi.Tmap.constant.TM_COORDTYPE;
import com.skt.tapi.stub.TApi;

@SuppressLint({ "NewApi", "NewApi" })
public class MainActivity extends Activity implements OnClickListener {

	private Tmap mTApi = null;
	private static String LOG_TAG ="LOG_TAG_";
	private static final int MSG_XML_CODE = 1;
		
	private EditText editAp;	// Edit 출발지
	private EditText editBp;	// Edit 도착지
	private Button BtnFind;		// Btn 길찾기
	int m_iTotalTime ;			// 총 소요시간
	double m_dTotalDistance ;	// 총 소요거리
	String m_strMypoint;		// Str 출발지
	String m_strEndpoint;		// Str 도착지
	Criteria criteria;			// 사용자 현재위치
	double m_dNowlat;			// 출발지 위도
	double m_dNowlng;			// 출발지 경도
	float m_fEndlat;			// 도착지 위도
	float m_fEndlng;			// 도착지 경도
	
	
	private Handler mInitCB = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			TextView tvConn = (TextView)findViewById(R.id.conn);
			switch(msg.what){
			case TApi.SERVICE_CONNECTED:
				Log.d(LOG_TAG,"CallBack Received[CONNECTED]");
		    	tvConn.setText("연결성공");
				break;
			case TApi.SERVICE_DISCONNECTED:
				Log.d(LOG_TAG, "Callback Received[DISCONNECTED]"); 
				break;
			 case TApi.SERVICE_BINDING_TIME_OUT: // Time Out
				 Log.d(LOG_TAG, "Callback Received[TIMEOUT]"); 
				 break;
			 case TApi.SERVICE_BLACKLIST: // BlackList 
				 Log.d(LOG_TAG, "Callback Received[Black List]");
				 break;
			 case TApi.SERVICE_CONNECT_FAIL: // connecet Error 
				 Log.d(LOG_TAG, "Callback Received[CONNECT ERROR]");
			    tvConn.setText("연결실패");
				 break;
			default:
				super.handleMessage(msg);
			}
		}
	};
	
	private Handler handler = new Handler(){
	     public void handleMessage(android.os.Message msg){
	    	switch (msg.what) {
			case MSG_XML_CODE:
				String url = "http://maps.google.com/maps/geo?q="+ m_strEndpoint +"&output=xml&key=";
				String [] coordinates = null;
				
				try {
					coordinates = XmlPullParsing.parser( XmlPullParsing.xmlInputstream(url) );
					if( coordinates != null ) {
						for(int i=0; i<coordinates.length; i++) {
							Log.d(LOG_TAG, "============> " + i+ "========="+ coordinates[i]);
						}
						m_fEndlng = Float.valueOf(coordinates[0]).floatValue();
				      	m_fEndlat = Float.valueOf(coordinates[1]).floatValue();
					}
					TmapConnected();
					Intender();  
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				break;

			default:
				break;
			}
	     }
	    };
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        
        mTApi = Tmap.getInstance(this);
        if(mTApi != null)
        	mTApi.initialize(mInitCB);
        else
        	Log.d(LOG_TAG,"mTApi.getInstance ERROR!!!");
        
        editAp = (EditText)findViewById(R.id.EdAp);
        editBp = (EditText)findViewById(R.id.EdBp);
        BtnFind = (Button)findViewById(R.id.BtnFind);
        BtnFind.setOnClickListener(this);
        
        LocationManager locationmanager;
        String context = Context.LOCATION_SERVICE;
        locationmanager=(LocationManager)getSystemService(context);
       
        criteria=new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
       
        String provider = locationmanager.getBestProvider(criteria, true);
       
        Location location = locationmanager.getLastKnownLocation(provider);
        try {
			updateWithNewLocation(location);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
        locationmanager.requestLocationUpdates(provider, 2000, 10, locationListener);
        
       editAp.setText(m_strMypoint);
       m_strEndpoint = "";
       
   		
    }
    
    @Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
    		callXml();
    		m_strMypoint = editAp.getText().toString();
    		m_strEndpoint = editBp.getText().toString();
	}
    
    void callXml(){
		Thread thread = new Thread(){
			public void run(){
				 Message msg = handler.obtainMessage(MSG_XML_CODE);
		  	     handler.sendMessage(msg);
			};
		};
		
		thread.start();
		try {
			thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

    
    private void Intender() {
        Intent it = new Intent(this, ResultMap.class);
        it.putExtra("Apoint", editAp.getText().toString()); 
        it.putExtra("Bpoint", editBp.getText().toString());
        it.putExtra("iTotalTime",m_iTotalTime );
        it.putExtra("dTotalDistance", m_dTotalDistance);
        startActivity(it);  
       }
    
    
   
	public void TmapConnected() throws ClientProtocolException, IOException{
    	// T Api 사용자 인증 - 테스트키
    	mTApi.requestInitialize("68da911f66cd92cbb2b6a64610db5739d41760d762350d5ea2e6a623bfce9419", null, null);
		
    	m_iTotalTime = 0;
    	m_dTotalDistance = 0;
    	
	    TmapPoint dept = new TmapPoint();
    	dept.szName = "";
    	dept.iCoordType = TM_COORDTYPE.E_COORD_BESSEL;
    	dept.fX = (float)m_dNowlng;
    	dept.fY =  (float)m_dNowlat;
    	
        TmapPoint dest = new TmapPoint();
    	dest.szName = "";
    	dest.iCoordType = TM_COORDTYPE.E_COORD_BESSEL;
    	dest.fX =  m_fEndlng;
    	dest.fY =  m_fEndlat;
    	
    	if(dest.fX != 0.0){
    		TmapResultRoute TmapResultroute = mTApi.requestRoute(dept, dest,NV_ROUTEFARETYPE.NV_ROUTE_CHARGED, 0, 0); 
    		m_iTotalTime = TmapResultroute.route.iTotalTime /60;
    		m_dTotalDistance = Double.parseDouble(String.format("%.1f", (double)TmapResultroute.route.iTotalDistance/1000));
    	}
    	
    }

	// 현재 위치 
		private void updateWithNewLocation(Location location) throws IOException {
	               String latlng;
	               if(location!=null)
	               {
	                       m_dNowlat = location.getLatitude();
	                       m_dNowlng = location.getLongitude();
	                       ReverseGeocode rgp = new ReverseGeocode();
	                       m_strMypoint = rgp.point2address(m_dNowlat, m_dNowlng, this);
	                       Log.d(LOG_TAG, "==========>" + rgp.point2address(m_dNowlat, m_dNowlng, this));
	               }
	               else
	               {
	                       latlng="현재 위치를 찾을수 없습니다.";
	               }
	        }
		private final LocationListener locationListener = new LocationListener() {
	        
	        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
	        	 //위치 프로바이더의 하드웨어 상태가 변경된 경우 어플리케이션을 업데이트한다.
	        }
	       
	        public void onProviderEnabled(String arg0) {
	        	   //위치 프로바이더가 활성화된 경우 애플리케이션을 업데이트 한다.
	        }
	       
	        public void onProviderDisabled(String arg0) {
	        	  //위치 프로바이더가 비활성화된 경우 애플리케이션을 업데이트 한다.
	                try {
						updateWithNewLocation(null);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	        }

			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				try {
					updateWithNewLocation(location);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	 };
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mTApi.requestDestroy();
    	mTApi.finalize();
		super.onDestroy();
	}

}
